package models

import (
	"NewEdu/utils"
	"context"
	"encoding/json"
	"fmt"
	"strings"
	"time"

	"github.com/beego/beego/v2/client/orm"
)

// TGoods 二手商品模型
type TGoods struct {
	ID          int       `orm:"column(id);auto" json:"id"`
	Title       string    `orm:"column(title);size(145)" json:"title"`
	Desc        string    `orm:"column(desc);size(245)" json:"desc"`
	Images      string    `orm:"column(images);size(300)" json:"images"`
	FromSN      string    `orm:"column(from_sn);size(45)" json:"from_sn"`
	FromName    string    `orm:"column(from_name);size(45)" json:"from_name"`
	Creattime   time.Time `orm:"column(creattime);type(datetime)" json:"creattime"`
	Kind        int       `orm:"column(kind)" json:"kind"`
	Status      int       `orm:"column(status)" json:"status"`
	NowPrice    float32   `orm:"column(now_price)" json:"now_price"`
	OriginPrice float32   `orm:"column(origin_price)" json:"origin_price"`
	Call        string    `orm:"column(call);size(45)" json:"call"`
}

func (t *TGoods) TableName() string {
	return "t_goods"
}

func init() {
	orm.RegisterModel(new(TGoods))
}

// AddTGoods 向数据库添加二手商品
func AddTGoods(goods *TGoods) (int64, error) {
	o := orm.NewOrm()
	return o.Insert(goods)
}

// GetTGoodsById 根据商品 ID 获取二手商品信息
func GetTGoodsById(id int) (*TGoods, error) {
	o := orm.NewOrm()
	goods := &TGoods{ID: id}
	err := o.Read(goods)
	if err != nil {
		return nil, err
	}
	return goods, nil
}

// GetAllTGoods 获取所有二手商品列表
func GetAllTGoods(query map[string]string, offset int64, limit int64) (ml []TGoods, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TGoods))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}

	var l []TGoods
	if _, err = qs.OrderBy("-id").Limit(limit, offset).All(&l); err == nil {

		return l, nil
	}
	return nil, err
}

// UpdateTGoods 更新二手商品信息
func UpdateTGoods(goods *TGoods) error {
	o := orm.NewOrm()
	_, err := o.Update(goods)
	return err
}

// DeleteTGoods 删除二手商品
func DeleteTGoods(id int) error {
	o := orm.NewOrm()
	_, err := o.Delete(&TGoods{ID: id})
	return err
}

// LoadTGoods2Redis 将二手商品信息加载到 Redis 中
func LoadTGoods2Redis() error {
	o := orm.NewOrm()
	qs := o.QueryTable(new(TGoods))
	var allGoods []*TGoods
	_, err := qs.All(&allGoods)
	if err != nil {
		return err
	}

	ctx := context.Background()
	for _, item := range allGoods {
		itemJson, err := json.Marshal(item)
		if err != nil {
			return err
		}
		cmd := utils.RedisClient.Set(ctx, fmt.Sprintf("goods:%d", item.ID), itemJson, 0)
		_, err = cmd.Result()
		if err != nil {
			return err
		}
	}
	return nil
}
